#
#    Copyright (C) 2016 Francisco Javier Parra <franparpe@openmailbox.org>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
#

from PyQt5.QtWidgets import QGroupBox, QWidget
from PyQt5.QtWidgets import QVBoxLayout

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar

from matplotlib.figure import Figure
from matplotlib import pyplot


from PyQt5 import QtCore

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s


class CamProfileGraph(QWidget):
    """This is the element that contains the cam
    profile
    """
    def __init__(self, parent):
        super(CamProfileGraph, self).__init__(parent)
        
        # Aesthetics
        #self.setFrameShape(self.StyledPanel)
        #self.setFrameShadow(self.Raised)

        # Group Box
        self.groupbox = QGroupBox(self)
        #self.groupbox.setTitle(_fromUtf8("Cam profile"))

        # The layout
        self.mainLayout = QVBoxLayout(self)
        self.mainLayout.addWidget(self.groupbox)
        # Group Box layout
        self.gboxVBox = QVBoxLayout(self.groupbox)

        # Create figure container
        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)
        self.gboxVBox.addWidget(self.canvas)
        
        # Toolbar
        self.toolBarCamProfile = NavigationToolbar(self.canvas, self.groupbox)
        self.gboxVBox.addWidget(self.toolBarCamProfile)

        # Initialize Graph
        self.InitDefaultGraph()

    def InitDefaultGraph(self):
        """ This method creates the default layout
        """
        self.camProfileGraph = self.figure.add_subplot(111)
        self.camProfileGraph.set_title(_fromUtf8("Cam profile"))
        self.camProfileGraph.grid(True)

    def genProfileUnilateral(self, camProfile,
                             offset=None,
                             rb=None):
        """Graphs the cam profile
        """
        self.camProfileGraph.clear()
        # self.camProfileGraph.set_title(_fromUtf8("Cam profile"))
        # self.camProfileGraph.spines['left'].set_position(('data', 0))
        # self.camProfileGraph.spines['bottom'].set_position(('data', 0))
        # self.camProfileGraph.spines['right'].set_position(('data', 0))
        # self.camProfileGraph.spines['top'].set_position(('data', 0))
        self.camProfileGraph.grid(True)
        self.camProfileGraph.set_aspect('equal', 'datalim')
        profX = []
        profY = []
        offsetX = []
        offsetY = []
        # maxRadius = 0
        for point in camProfile:
            profX.append(point[0])
            profY.append(point[1])
            # distance2Profile = math.hypot(point[0], point[1])
            # if maxRadius < distance2Profile:
            #     maxRadius = math.hypot(point[0],
            #                            point[1])
            # else:
            #     pass

        # Preparing the circle that draws the maximum
        # maxCircle = pyplot.Circle((0, 0),
        #                           radius=maxRadius,
        #                           color='k',
        #                           linestyle='dashed',
        #                           fill=False)
        # self.camProfileGraph.add_patch(maxCircle)

        if offset is not None:
            for point in offset:
                offsetX.append(point[0])
                offsetY.append(point[1])
            self.camProfileGraph.plot(offsetX,
                                      offsetY,
                                      "r-",
                                      lw=0.5)
        else:
            pass
            
        if rb is None:
            pass
        elif rb is not None:
            baseCircle = pyplot.Circle((0, 0),
                                       radius=rb,
                                       color='m',
                                       linestyle='dashed',
                                       fill=False)
            self.camProfileGraph.add_patch(baseCircle)
        else:
            print("error")

        
        self.camProfileGraph.plot(profX, profY, 'b-',
                                  lw=1.4)
        # Add a point in the center
        self.camProfileGraph.plot(0, 0, 'ro')
        self.canvas.draw()

    def genProfileBilateral(self, camProfile1,
                            camProfile2,
                            offset1=None,
                            offset2=None,
                            rb=None,
                            rb2=None):
        """Graphs the cam profile
        """
        self.camProfileGraph.clear()
        # self.camProfileGraph.set_title(_fromUtf8("Cam profile"))
        # self.camProfileGraph.spines['left'].set_position(('data', 0))
        # self.camProfileGraph.spines['bottom'].set_position(('data', 0))
        # self.camProfileGraph.spines['right'].set_position(('data', 0))
        # self.camProfileGraph.spines['top'].set_position(('data', 0))
        self.camProfileGraph.grid(True)
        self.camProfileGraph.set_aspect('equal', 'datalim')
        profX1 = []
        profY1 = []
        offsetX1 = []
        offsetY1 = []

        # Now for the second profile
        profX2 = []
        profY2 = []
        offsetX2 = []
        offsetY2 = []
        maxRadius1 = 0
        maxRadius2 = 0
        for point in camProfile1:
            profX1.append(point[0])
            profY1.append(point[1])
            # distance2Profile = math.hypot(point[0], point[1])
            # if maxRadius1 < distance2Profile:
            #     maxRadius1 = math.hypot(point[0],
            #                             point[1])
            # else:
            #     pass

        # # Preparing the circle that draws the maximum
        # maxCircle1 = pyplot.Circle((0, 0),
        #                            radius=maxRadius1,
        #                            color='k',
        #                            linestyle='dashed',
        #                            fill=False)
        # self.camProfileGraph.add_patch(maxCircle1)

        if offset1 is not None:
            for point in offset1:
                offsetX1.append(point[0])
                offsetY1.append(point[1])
            self.camProfileGraph.plot(offsetX1,
                                      offsetY1,
                                      "r-",
                                      lw=0.5)
        else:
            pass
            
        if rb is None:
            pass
        elif rb is not None:
            baseCircle1 = pyplot.Circle((0, 0),
                                        radius=rb,
                                        color='m',
                                        linestyle='dashed',
                                        fill=False)
            self.camProfileGraph.add_patch(baseCircle1)
        else:
            print("error")

        # The second profile
        for point in camProfile2:
            profX2.append(point[0])
            profY2.append(point[1])
            # distance2Profile = math.hypot(point[0], point[1])
            # if maxRadius2 < distance2Profile:
            #     maxRadius2 = math.hypot(point[0],
            #                             point[1])
            # else:
            #     pass

        # # Preparing the circle that draws the maximum
        # maxCircle2 = pyplot.Circle((0, 0),
        #                            radius=maxRadius2,
        #                            color='k',
        #                            linestyle='dashdot',
        #                            fill=False)
        # self.camProfileGraph.add_patch(maxCircle2)

        if offset2 is not None:
            for point in offset2:
                offsetX2.append(point[0])
                offsetY2.append(point[1])
            self.camProfileGraph.plot(offsetX2,
                                      offsetY2,
                                      "r-",
                                      lw=0.5)
        else:
            pass

        self.camProfileGraph.plot(profX1, profY1, '-', lw=1.4)
        self.camProfileGraph.plot(profX2, profY2, '-', lw=1.4)
        # Add a point in the center
        self.camProfileGraph.plot(0, 0, 'ro')
        self.canvas.draw()

